package myJs.admin

import myJs.Utils._
import myJs.myPkg._
import myJs.myPkg.jquery._
import scalatags.Text.all._

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation._
import myJs.Implicits._
import shared.VarTool
import myJs.Utils._

import scala.collection.immutable.SeqMap


/**
 * Created by yz on 2019/3/6
 */
@JSExportTopLevel("DataManage")
object DataManage {

  val ids = ArrayBuffer[String]()
  val tableId = "table"
  val headerMap = SeqMap("barcode" -> "Tumor_Sample_Barcode", "sampleName" -> "Tumor_Sample_Name",
    "treeCode" -> "OncoTree_Code", "refGene" -> "Gene.refGene")
  val fieldNames=headerMap.keyList ::: VarTool.dataHeaders.filterNot { x =>
    headerMap.valueList.contains(x)
  }

  @JSExport("init")
  def init = {
    initTable
    refreshTableView
    refreshTableData()
  }

  def initTable = {
    val table = tableId
    val checkColumn = ColumnOptions.field("checked").checkbox(true)
    val columnNames = fieldNames
    val columns = js.Array(checkColumn) ++ columnNames.map { columnName =>
      val title =headerMap.getOrElse(columnName,columnName)
      ColumnOptions.field(columnName).title(title).sortable(true)
    }.concat(operateColumn)
    val options = TableOptions.columns(columns)
    $(s"#${tableId}").bootstrapTable(options)
  }

  def refreshTableView = {
    val names = fieldNames
    val nameMap = names.map { x =>
      (x -> headerMap.getOrElse(x,x))
    }
    val html = nameMap.map { case (field,name) =>
      label(marginRight := 15,
        input(`type` := "checkbox", checked, value := field, onclick := s"Utils.setColumns('${field}','${tableId}')", name)
      )
    }.mkString
    $("#checkbox").html(html)
    val hideColumns = names.drop(6)
    hideColumns.foreach { x =>
      $("#table").bootstrapTable("hideColumn", x)
      $(s"input:checkbox[value='${x}']").attr("checked", false)
    }
    bindEvt
  }

  def bindEvt = {
    $("#table").on("check.bs.table", () => getIds)
    $("#table").on("uncheck.bs.table", () => getIds)
    $("#table").on("check-all.bs.table", () => getIds)
    $("#table").on("uncheck-all.bs.table", () => getIds)
    $("#table").on("page-change.bs.table", () => getIds)
  }

  def getIds = {
    ids.clear()
    val arrays = g.$("#table").bootstrapTable("getSelections").asInstanceOf[js.Array[js.Dictionary[String]]]
    ids ++= arrays.map { x =>
      x("id")
    }
    if (ids.isEmpty) $("#deleteButton").attr("disabled", true) else
      $("#deleteButton").attr("disabled", false)
  }

  val operateColumn = js.Array(
    ColumnOptions.field("operate").title("操作").formatter(operateFmt).filterControl("clear")
  )

  def refreshTableData(f: () => js.Any = () => ()) = {
    val url = g.jsRoutes.controllers.DataController.getAllData().url.toString
    val ajaxSettings = JQueryAjaxSettings.url(url).`type`("get").success { (data, status, e) =>
      $("#table").bootstrapTable("load", data)
      f()
    }
    $.ajax(ajaxSettings)
  }

  @JSExport("deletes")
  def deletes = {
    val dict = js.Dictionary(
      "title" -> "",
      "text" -> "确定要删除选中的数据吗？",
      "type" -> "warning",
      "showCancelButton" -> true,
      "showConfirmButton" -> true,
      "confirmButtonClass" -> "btn-danger",
      "confirmButtonText" -> "确定",
      "closeOnConfirm" -> false,
      "cancelButtonText" -> "取消",
    )
    g.swal(dict, () => {
      val data = js.Dictionary(
        "ids" -> ids.toJSArray
      )
      val url = g.jsRoutes.controllers.adminC.DataController.deletes().url.toString
      val ajaxSettings = JQueryAjaxSettings.url(url).contentType("application/json").
        `type`("post").data(JSON.stringify(data)).success { (data, status, e) =>
        refreshTableData { () =>
          Swal.swal(SwalOptions.title("成功").text("删除数据成功!").`type`("success"))
        }
        getIds
      }.error { (data, status, e) =>
        g.swal("错误", "删除失败！", "error")
      }
      $.ajax(ajaxSettings)
    })
  }

  @JSExport("delete")
  def delete(number: String) = {
    val dict = js.Dictionary(
      "title" -> "",
      "text" -> "确定要删除此数据吗？",
      "type" -> "warning",
      "showCancelButton" -> true,
      "showConfirmButton" -> true,
      "confirmButtonClass" -> "btn-danger",
      "confirmButtonText" -> "确定",
      "closeOnConfirm" -> false,
      "cancelButtonText" -> "取消",
    )
    g.swal(dict, () => {
      val url = g.jsRoutes.controllers.adminC.DataController.deleteById().url.toString
      val ajaxSettings = JQueryAjaxSettings.url(s"${url}?id=${number}").
        `type`("get").contentType("application/json").success { (data, status, e) =>
        refreshTableData{()=>
          Swal.swal(SwalOptions.title("成功").text("删除成功!").`type`("success"))
        }
      }.error { (data, status, e) =>
        g.swal("错误", "删除失败！", "error")
      }
      $.ajax(ajaxSettings)
    })
  }

  @JSExport("operateFmt")
  def operateFmt: js.Function = {
    (v: js.Any, row: js.Dictionary[js.Any]) =>
      val deleteStr = a(
        title := "删除",
        onclick := s"DataManage.delete('${row("id")}')",
        cursor.pointer,
        span(
          em(cls := "fa fa-close")
        )
      )
      Array(deleteStr).mkString("&nbsp;")
  }

}
